package com.grass.cropTradingCenter.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import io.swagger.models.auth.In;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TokenUtil {

    /**
     * 过期时间 1月
     */
    public static final long EXPIRE_TIME = 1000L * 60 * 60 * 24 * 30;

    /**
     * token刷新时间 1小时
     */
    public static final long REFRESH_TIME = 1000L * 60 * 60;

    // 私钥
    private static final String SECRET = "80ed3c7337db431fb27fb22c9a9187fe";


    /**
     * 通过 userId 生成token
     * @param userId
     * @return
     */
    public static String getToken(int userId, String type){
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        String token = "";
        token = JWT
                .create()
                .withClaim("userId", userId)
                .withClaim("type", type)
                .withClaim("timeStamp", System.currentTimeMillis())
                .withExpiresAt(date)
                .sign(Algorithm.HMAC256(SECRET));

        return token;

    }
    public static String getToken(String userId, String type){
        return getToken(Integer.parseInt(userId), type);
    }

    /**
     * 通过token获取userId
     * @param token
     * @return
     */
    public static int getUserIdByToken(String token){
        DecodedJWT decodedJWT = JWT
                .require(Algorithm.HMAC256(SECRET))
                .build()
                .verify(token);
        Claim userId = decodedJWT.getClaim("userId");
        return Integer.parseInt(userId.asString());
    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public static Map<String, String> parseToken(String token) {
        HashMap<String, String> map = new HashMap<String, String>();
        DecodedJWT decodedjwt = JWT.require(Algorithm.HMAC256(SECRET))
                .build().verify(token);
        Claim userId = decodedjwt.getClaim("userId");
        Claim timeStamp = decodedjwt.getClaim("timeStamp");
        Claim type = decodedjwt.getClaim("type");

        map.put("userId", userId.asInt().toString());
        map.put("timeStamp", timeStamp.asLong().toString());
        map.put("type", type.asString());
        return map;
    }

}
